<?php
namespace app\admin\controller;

use think\Db;
use app\admin\model\DepartmentModel;

class Commit extends Base{
	/**
	 * [公共]
	 */
	# -< Common >---------------------------------------------------------------
	public function getCurDepart() {
		return DB::name('department')->alias('depart')
			->join('role role','depart.id = role.department_id')
			->join('user user','user.role_id = role.id')
			->where('user.id',session('id'))
			->field('depart.name,depart.id')->find();
	}

	public function getDepartOpt() {
		$DepartModel = new DepartmentModel();
		$departs = $DepartModel->getCanSeeDepart(session('id'));
		$departs = $this->arr2tree($departs);
		$depart_opt = $this->getNameByTree($departs);
		return $depart_opt;
	}

	/**
	 * [日报表]
	 */
	# -< Day >------------------------------------------------------------------
	public function Day() {
		$company = DB::name('users_company')->where([
			"uid" => session("id")
		])->find();
		$rptDate = input("rptDate");
		if(empty($company)){
			$this->error("您还没有注册为企业",url("Tablequery/Day"));
		}
		$buy = DB::name('goods_cate')
			->where('commid','in',explode(",",$company['buy']))
			->field("name,commid")
			->order("id desc")->select();
		$sell = DB::name('goods_cate')
			->where('commid_2','in',explode(",",$company['sell']))
			->field("name,commid_2")
			->order("id desc")->select();
		$this->assign([
			'Company' => $company,
			'Buy' => $buy,
			'Sell' => $sell,
			'rptDate' => $rptDate
		]);
		if($rptDate == ''){
			return $this->fetch();
		}else{
			return $this->fetch("write_day");
		}
	}

	public function Day_check() {
		$param = input("post.");
		$check =  DB::name("table_day")->where([
			'company_id' => $param['company_id'],
			'rpt_date' => $param['rptDate'] / 1000
		])->count();
		if($check == 0){
			return ['code'=>1,'msg'=>'success'];
		}else{
			return ['code'=>0,'msg'=>'该日期的报表已经填写'];
		}
	}

	public function saveDay() {
		$param = input("post.");
		$rpt_date = $param['rpt_date'] / 1000;
		$is_save = DB::name("table_day")->where([
			'company_id' => $param['company_id'],
			'rpt_date' => $rpt_date
		])->count();
		$is_commit = DB::name("table_day")->where([
			'company_id' => $param['company_id'],
			'rpt_date' => $rpt_date
		])->value("is_commit");
		$is_examine = DB::name("table_day")->where([
			'company_id' => $param['company_id'],
			'rpt_date' => $rpt_date
		])->value("is_examine");
		if($is_commit == 1){
			return ['code'=>0,'msg'=>'已提交的报表不能修改'];
		}
		if($is_examine == 1){
			return ['code'=>0,'msg'=>'已审核的报表不能修改'];
		}
		$data = $param;
		$data['rpt_date'] = $rpt_date;
		$data['form'] = $this->Arr2XML($param);
		$content = [
			'userId' => $param['userId'],
			'rptDate' => date("Y-m-d",$rpt_date),
			'serviceStationReport' => $param['content']
		];
		$content = $this->Arr2XML_day($content);
		$data['content'] = $content;
		unset($data['userId']);
		if($is_save == 0){
			$res = DB::name("table_day")->insert($data);
		}else{
			$res = DB::name("table_day")->where([
				'company_id' => $param['company_id'],
				'rpt_date' => $rpt_date
			])->update($data);
		}
		if($res !== false){
			return ['code'=>1,'msg'=>'保存成功'];
		}else{
			return ['code'=>0,'msg'=>'保存失败'];
		}
	}

	public function Arr2XML_day($arr) {
		$xml = '<?xml version="1.0" encoding="UTF-8"?>';
		$xml .= '<serviceStation>';
		$xml .= '<userId>'.$arr['userId'].'</userId>';
		$xml .= '<rptDate>'.$arr['rptDate'].'</rptDate>';
		foreach($arr['serviceStationReport'] as $v){
			$xml .= '<serviceStationReport>';
			$xml .= '<code>'.$v['code'].'</code>';
			$xml .= '<name>'.$v['name'].'</name>';
			$xml .= '<countyType>'.$v['countyType'].'</countyType>';
			$xml .= '<buyOrder>'.$v['buyOrder'].'</buyOrder>';
			$xml .= '<saleOrder>'.$v['saleOrder'].'</saleOrder>';
			foreach($v['serviceStationCommodity'] as $va){
				$xml .= '<serviceStationCommodity>';
				$xml .= '<commId>'.$va['commId'].'</commId>';
				$xml .= '<money>'.$va['money'].'</money>';
				$xml .= '</serviceStationCommodity>';
			}
			$xml .= '</serviceStationReport>';
		}
		$xml .= '</serviceStation>';
		return $xml;
	}

	public function CommitDay() {
		$table_id = input('post.table_id');
		$table = DB::name("table_day")->where("id",$table_id)->find();
		if($table['is_examine'] == 0){
			return ['code'=>0,'msg'=>'没有审核通过不能提交'];
		}
		if($table['is_commit'] == 1){
			return ['code'=>0,'msg'=>'该表格已经提交，请勿重复提交'];
		}
		DB::startTrans();
		try{
			# 上报国家
			$api_res = $this->sendXML2API($table['content']);
			if(isset($api_res['out']) && !empty($api_res['out'])){
				# 写入统计表
				$data = [];
				$rows = $this->XML2Arr($table['form'])['content'];
				foreach($rows as $k => $v){
					if($k % 2 == 0){
						$data[] = [
							'code' => $v['code'],
							'name' => $v['name'],
							'county_type' => $v['countyType'],
							'depart_id' => $table['depart_id'],
							'rpt_date' => $table['rpt_date'],
							'buy_order' => $v['buyOrder'],
							'buy_commid' => $v['commId'],
							'buy_money' => $v['money'],
							'sale_order' => $v['saleOrder'],
							'sell_commid' => $rows[$k+1]['commId'],
							'sell_money' => $rows[$k+1]['money'],
							'create_uid' => $table['create_uid'],
						];
					}
				}
				foreach($data as $val){
					DB::name("statistics_day")->insert($val);
				}
				# 更改状态
				DB::name("table_day")->where("id",$table_id)->update(['is_commit'=>1]);
			}else{
				return ['code'=>0,'msg'=>'国家接口连接错误'];
			}
			DB::commit();
			return ['code'=>1,'msg'=>'表格提交成功'];
		}catch(\Exception $e){
			DB::rollback();
			return ['code'=>0,'msg'=>'表格提交失败：'.$e->getMessage()];
		}
	}

	/**
	 * [月报表]
	 */
	# -< Month >----------------------------------------------------------------
	public function Month(){
		$rptDate = input('get.rptDate');
		if($rptDate == ''){
			return $this->fetch();
		}else{
			$depart = $this->getCurDepart();
			$TimeArr = date_parse_from_format('Y年m月',$rptDate);
			$time = mktime(0,0,0,$TimeArr['month'],01,$TimeArr['year']);
			$userArr = DB::name('department')->alias('depart')
						->join('role role','depart.id = role.department_id')
						->join('user user','user.role_id = role.id')
						->where('depart.id',$depart['id'])
						->where('user.register_status',2)
						->column('user.id');
			$company = DB::name('users_company')->where([
				'depart_id' => $depart['id'],
				'uid' => ['in',$userArr]
			])->column('name');
			$isSaved = DB::name('table_month')->where([
				'rpt_date' => $time,
				'depart_id' => $depart['id']
			])->value('id');
			if($isSaved != ''){
				$this->assign([
					'isSaved' => 1
				]);
				return $this->fetch();
			}
			$this->assign([
				'rptDate' => $rptDate,
				'depart' => $depart,
				'company' => $company
			]);
			return $this->fetch('write_month');
		}
	}

	public function saveMonth(){
		$param = input('post.');
		$TimeArr = date_parse_from_format('Y年m月',$param['rptDate']);
		$time = mktime(0,0,0,$TimeArr['month'],01,$TimeArr['year']);
		$xml = $this->arr2XML($param);
		$inData = [
			'rpt_date' => $time,
			'depart_name' => $param['departName'],
			'depart_id' => $param['departId'],
		    'link_man' => $param['linkMan'],
		    'link_type' => $param['linkType'],
			'content' => $xml,
			'create_uid' => session('id')
		];
		$isSaved = DB::name('table_month')->where([
			'rpt_date' => $time,
			'depart_id' => $param['departId']
		])->value('id');
		$isCommit = DB::name('table_month')->where([
			'rpt_date' => $time,
			'depart_id' => $param['departId']
		])->value('is_commit');
		if($isCommit != 0){
			return ['code'=>0,'msg'=>'表格已提交,不能再修改','data'=>''];
		}
		$isExamine = DB::name('table_month')->where([
			'rpt_date' => $time,
			'depart_id' => $param['departId']
		])->value('examine');
		if($isExamine == 1){
			return ['code'=>0,'msg'=>'表格已审核,不能再修改','data'=>''];
		}
		if($isSaved == ''){
			$res = DB::name('table_month')->insert($inData);
		}else{
			$res = DB::name('table_month')->where('id',$isSaved)->update($inData);
		}
		if($res !== false){
			return ['code'=>1,'msg'=>'表格保存成功','data'=>''];
		}else{
			return ['code'=>0,'msg'=>'表格保存失败','data'=>''];
		}
	}

	public function CommitMonth() {
		$param = input("post.");
		$TimeArr = date_parse_from_format('Y年m月',$param['rptDate']);
		$where = [
			'rpt_date' => mktime(0,0,0,$TimeArr['month'],01,$TimeArr['year']),
			'depart_name' => $param['departName'],
			'depart_id' => $param['departId'],
		];
		$tableData = DB::name('table_month')->where($where)->find();
		if($tableData['is_commit'] != 0){
			return ['code'=>0,'msg'=>'该表已提交,请勿重复提交','data'=>''];
		}
		if($tableData['examine'] != 1){
			return ['code'=>0,'msg'=>'审核后才能提交','data'=>''];
		}
		$tableCt = $this->XML2Arr($tableData['content']);
		$TimeArr = date_parse_from_format('Y年m月',$tableCt['rptDate']);
		$ctime = mktime(0,0,0,$TimeArr['month'],01,$TimeArr['year']);
		DB::startTrans();
		try{
			# 写入统计数据
			// print_r($tableCt);die;
			// 1.电商扶贫情况汇总
			$data_1 = [
				'depart_id' => $tableCt['departId'],
				'depart_name' =>  $tableCt['departName'],
				'rpt_date' =>  $ctime,
				'create_uid' => $tableData['create_uid'],
				'cover_0' => $tableCt['form1']['poorVillageCount'],
				'cover_1' => $tableCt['form1']['poorVillageFill'],
				'cover_3' => $tableCt['form1']['poorNoVlgPeople'],
				'help_0' => $tableCt['form1']['poorSum'],
				'help_2' => $tableCt['form1']['poorPeopleSum'],
				'help_3' => $tableCt['form1']['poorSumPeopleSum'],
				'help_4' => $tableCt['form1']['helpPoorSale'],
				'help_6' => $tableCt['form1']['helpAddProfit'],
				'help_8' => $tableCt['form1']['poorAvgProfit'],
				'train_0' => $tableCt['form1']['jobPeopleCount'],
				'train_2' => $tableCt['form1']['jobPoorCount'],
				'train_3' => $tableCt['form1']['poorNoVlgPeople'],
			];
			if($data_1['cover_0'] && $data_1['cover_1']){
				$data_1['cover_2'] = $data_1['cover_1'] / $data_1['cover_0'];
			}
			DB::name("statistics_recfp")->insert($data_1);
			// 2.公共服务体系建设情况
			$county = 0;$county_in = 0;
			$town = 0;$town_in = 0;
			$country = 0;$country_in = 0;
			foreach($tableCt['form2']['servicePlatforms'] as $v2){
				switch ($v2['buildType']) {
					case '1':
						$county += 1;
						if($v2['isShare'] == 'true'){
							$county_in += 1;
						}break;
					case '2':
						$town += 1;
						if($v2['isShare'] == 'true'){
							$town_in += 1;
						}break;
					case '3':
						$country += 1;
						if($v2['isShare'] == 'true'){
							$country_in += 1;
						}break;
				}
			}
			$data_2 = [
				'depart_id' => $tableCt['departId'],
				'depart_name' =>  $tableCt['departName'],
				'rpt_date' =>  $ctime,
				'create_uid' => $tableData['create_uid'],
				'county' => $county,
				'county_in' => $county_in,
				'town' => $town,
				'town_in' => $town_in,
				'country' => $country,
				'country_in' => $country_in,
			];
			DB::name("statistics_pubservice")->insert($data_2);
			// 3.物流配送体系建设情况
			$county_num = 0;$town_num = 0;$country_num = 0;
			foreach($tableCt['form3']['transportSystems'] as $v3){
				switch ($v3['buildType']) {
					case '1': $county_num += 1;break;
					case '2': $town_num += 1;break;
					case '3': $country_num += 1;break;
				}
			}
			$data_3 = [
				'depart_id' => $tableCt['departId'],
				'depart_name' =>  $tableCt['departName'],
				'rpt_date' =>  $ctime,
				'create_uid' => $tableData['create_uid'],
				'receive_num' => $tableCt['form3']['receiveNum'],
				'send_num' => $tableCt['form3']['sendNum'],
				'county_num' => $county_num,
				'town_num' => $town_num,
				'country_num' => $country_num
			];
			if($tableCt['form3']['isCombine'] == "true"){
 				$data_3['is_combine'] = 1;
			}else{
				$data_3['is_combine'] = 0;
			}
			DB::name("statistics_logistics")->insert($data_3);
			// 4.农村电子商务情况汇总
			$data_4 = [
				'depart_id' => $tableCt['departId'],
				'depart_name' =>  $tableCt['departName'],
				'rpt_date' =>  $ctime,
				'create_uid' => $tableData['create_uid'],
				'net_sale' => $tableCt['form4']['netSale'],
				'suk' => $tableCt['form4']['newSaleCount']
			];
			DB::name("statistics_recbusiness")->insert($data_4);
			// 5.农村电商培训情况汇总
			$data_5 = [
				'depart_id' => $tableCt['departId'],
				'depart_name' =>  $tableCt['departName'],
				'rpt_date' =>  $ctime,
				'create_uid' => $tableData['create_uid'],
				'train_sum' => $tableCt['form5']['trainSum'],
				'gov_count' => $tableCt['form5']['govCount'],
				'farmer_count' => $tableCt['form5']['farmerCount'],
				'poor_count' => $tableCt['form5']['poorCount'],
				'disable_count' => $tableCt['form5']['disableCount'],
				'drive_job' => $tableCt['form5']['driveJob'],
				'netcom_count' => $tableCt['form5']['netComCount'],
				'netcom_newcount' => $tableCt['form5']['netComNewCount'],
				'company_count' => $tableCt['form5']['companyCount'],
				'company_newcount' => $tableCt['form5']['companyNewCount'],
				'people_count' => $tableCt['form5']['peopleCount'],
				'people_newcount' => $tableCt['form5']['peopleNewCount'],
			];
			DB::name("statistics_rectrain")->insert($data_5);
			// 6.资金使用情况汇总
			$data_6 = [
				'depart_id' => $tableCt['departId'],
				'depart_name' =>  $tableCt['departName'],
				'rpt_date' =>  $ctime,
				'create_uid' => $tableData['create_uid'],
				'center_money' => 0,
				'center_pay' => 0,
				'local_money' => 0,
				'company_pay' => 0
			];
			foreach($tableCt['form6']['finances'] as $v6){
				if($v6['centerMoney']){
					$data_6['center_money'] += $v6['centerMoney'];
				}
				if($v6['centerPay']){
					$data_6['center_pay'] += $v6['centerPay'];
				}
				if($v6['localMoney']){
					$data_6['local_money'] += $v6['localMoney'];
				}
				if($v6['companyPay']){
					$data_6['company_pay'] += $v6['companyPay'];
				}
			}
			DB::name("statistics_capitaluse")->insert($data_6);
			# 写入GIS数据
			// 1.建档立卡贫困村
			foreach($tableCt['form1']['poorVillages'] as $v){
				if($v['lonlat'] != ''){
					DB::name('map_gis')->insert([
						'type' => 1,
						'lat' => explode(',',$v['lonlat'])[2],
						'lng' => explode(',',$v['lonlat'])[1],
						'depart_id' => $tableCt['departId'],
						'c_time' => $ctime
					]);
				}
			}
			// 2.公共服务体系
			foreach($tableCt['form2']['servicePlatforms'] as $v){
				if($v['lonlat'] != ''){
					DB::name('map_gis')->insert([
						'type' => 2,
						'lat' => explode(',',$v['lonlat'])[2],
						'lng' => explode(',',$v['lonlat'])[1],
						'depart_id' => $tableCt['departId'],
						'c_time' => $ctime
					]);
				}
			}
			// 3.物流配送体系
			foreach($tableCt['form3']['transportSystems'] as $v){
				if($v['lonlat'] != ''){
					DB::name('map_gis')->insert([
						'type' => 3,
						'lat' => explode(',',$v['lonlat'])[2],
						'lng' => explode(',',$v['lonlat'])[1],
						'depart_id' => $tableCt['departId'],
						'c_time' => $ctime
					]);
				}
			}
			// 4.农村产品上行
			foreach($tableCt['form4']['projectBuilds'] as $v){
				if($v['lonlat'] != ''){
					DB::name('map_gis')->insert([
						'type' => 4,
						'lat' => explode(',',$v['lonlat'])[2],
						'lng' => explode(',',$v['lonlat'])[1],
						'depart_id' => $tableCt['departId'],
						'c_time' => $ctime
					]);
				}
			}
			// 5.农村电商培训
			foreach($tableCt['form5']['trainProjects'] as $v){
				if($v['lonlat'] != ''){
					DB::name('map_gis')->insert([
						'type' => 5,
						'lat' => explode(',',$v['lonlat'])[2],
						'lng' => explode(',',$v['lonlat'])[1],
						'depart_id' => $tableCt['departId'],
						'c_time' => $ctime
					]);
				}
			}
			# 修改提交状态和提交时间
			DB::name('table_month')->where($where)->update([
				'is_commit' => 1,'commit_time' => time()
			]);
			DB::commit();
			return ['code'=>1,'msg'=>'提交成功','data'=>''];
		}catch(\Exception $e){
			DB::rollback();
			return ['code'=>0,'msg'=>'提交失败:'.$e->getMessage(),'data'=>''];
		}
	}

	/**
	 * [年报表]
	 */
	# -< Year >-----------------------------------------------------------------
	public function Year() {
		$rptDate = input('get.rpt_date');
		if($rptDate != ""){
			$this->assign([
				'rpt_date' => $rptDate,
				'depart_name' => input('get.depart_name'),
				'depart_id' => input('get.depart_id')
			]);
			return $this->fetch('write_year');
		}
		return $this->fetch();
	}

	public function CheckYear() {
		$year = input('post.rptDate');
		if($year == ''){
			return ['code'=>0,'msg'=>'请选择报表年份'];
		}
		$time = strtotime($year."0101000000");
		$depart = $this->getCurDepart();
		$isSaved = DB::name('table_year')->where([
			'rpt_date' => $time,
			'depart_id' => $depart['id']
		])->value('id');
		if($isSaved != ''){
			return ['code'=>0,'msg'=>'该年份的报表已经上报'];
		}else{
			$data = [
				'rpt_date' => date("Y",$time),
				'depart_name' => $depart['name'],
				'depart_id' => $depart['id']
			];
			return ['code'=>1,'msg'=>'','data'=>$data];
		}
	}

	public function SaveYear() {
		$param = input("post.");
		$xml = $this->Arr2XML($param);
		$time = strtotime($param['rptDate']."0101000000");
		$inData = [
			'rpt_date' => $time,
			'depart_name' => $param['departName'],
			'depart_id' => $param['departId'],
		    'link_man' => $param['linkMan'],
		    'link_type' => $param['linkType'],
			'content' => $xml,
			'create_uid' => session('id')
		];
		$info = DB::name('table_year')->where([
			'rpt_date' => $time,
			'depart_id' => $param['departId']
		])->find();
		if($info['is_commit'] == 1){
			return ['code'=>0,'msg'=>'表格已提交,不能再修改','data'=>''];
		}
		if($info['examine'] == 1){
			return ['code'=>0,'msg'=>'表格已审核,不能再修改','data'=>''];
		}
		if($info['id'] == ''){
			$res = DB::name('table_year')->insert($inData);
		}else{
			$res = DB::name('table_year')->where('id',$info['id'])->update($inData);
		}
		if($res !== false){
			return ['code'=>1,'msg'=>'表格保存成功','data'=>''];
		}else{
			return ['code'=>0,'msg'=>'表格保存失败','data'=>''];
		}
	}

	public function CommitYear() {
		$param = input("post.");
		$where = [
			'rpt_date' => $time = strtotime($param['rptDate']."0101000000"),
			'depart_id' => $param['departId'],
		];
		$tableData = DB::name('table_year')->where($where)->find();
		if($tableData['is_commit'] != 0){
			return ['code'=>0,'msg'=>'该表已提交,请勿重复提交','data'=>''];
		}
		if($tableData['examine'] != 1){
			return ['code'=>0,'msg'=>'审核后才能提交','data'=>''];
		}
		DB::startTrans();
		try{
			# 修改提交状态和提交时间
			DB::name('table_year')->where($where)->update([
				'is_commit' => 1,'commit_time' => time()
			]);
			$tableCt = $this->XML2Arr($tableData['content']);
			# 写入统计数据
			// print_r($tableCt);
			# 写入GIS数据
			DB::commit();
			return ['code'=>1,'msg'=>'提交成功','data'=>''];
		}catch(\Exception $e){
			DB::rollback();
			return ['code'=>0,'msg'=>'提交失败','data'=>''];
		}
	}

	/**
	 * [资金管理-企业表]
	 */
	# -< Capital >--------------------------------------------------------------
	public function Capital() {
		$depart = $this->getCurDepart();
		$year = date("Y",time());
		$moneyLimit = DB::name('capital_mgr')->where([
			'depart_id' => $depart['id'],'year' => $year
		])->value("capital");
		if($moneyLimit == ''){
			$this->error("请先设置今年的资金",url("capitalmgr/index"));
		}
		$this->assign([
			'depart' => $depart,'moneyLimit' => $moneyLimit
		]);
		return $this->fetch('write_capital');
	}

	public function saveCapital() {
		$param = input('post.');
		if($param['departId'] == "" || $param['departName'] == ""){
			return ['code'=>0,'msg'=>'数据丢失，请刷新页面重新填写'];
		}
		if($param['linkMan'] == "" || $param['linkType'] == ""){
			return ['code'=>0,'msg'=>'请填写填表人和联系方式'];
		}
		$check = DB::name('table_capital')->where([
			'depart_id' => $param['departId'],
			'depart_name' => $param['departName'],
			'enter_name' => $param['enterName'],
		])->find();
		$data = [
			'depart_id' => $param['departId'],
			'depart_name' =>$param['departName'],
			'link_man' =>$param['linkMan'],
			'link_type' =>$param['linkType'],
			'enter_name' =>$param['enterName'],
			'create_uid' => session('id'),
			'content' => $this->arr2XML($param)
		];
		if(!empty($check)){
			if($check['is_commit'] != 0){
				return ['code'=>0,'msg'=>'已提交的报表不能修改'];
			}
			$res = DB::name('table_capital')->where([
				'depart_id' => $param['departId'],
				'depart_name' => $param['departName'],
				'enter_name' => $param['enterName'],
			])->update($data);
		}else{
			$res = DB::name('table_capital')->insert($data);
		}
		if($res !== false){
			return ['code'=>1,'msg'=>'表格保存成功','data'=>''];
		}else{
			return ['code'=>0,'msg'=>'表格保存失败','data'=>''];
		}
	}

	public function checkCapital() {
		$param = input("post.");
		$check = DB::name('table_capital')->where([
			'depart_id' => $param['departId'],
			'depart_name' => $param['departName'],
			'enter_name' => $param['enterName'],
		])->count();
		if($check != 0){
			return ['code'=>0,'msg'=>'该企业报表已经存在'];
		}else{
			return ['code'=>1,'msg'=>''];
		}
	}

	public function CommitCapital() {
		$param = input("post.");
		$where = [
			'depart_id' => $param['departId'],
			'enter_name' => $param['enterName']
		];
		$tableData = DB::name('table_capital')->where($where)->find();
		if($tableData['is_commit'] == 1){
			return ['code'=>0,'msg'=>'该表已提交,请勿重复提交'];
		}
		DB::startTrans();
		try{
			# 修改提交状态和提交时间
			DB::name('table_capital')->where($where)->update(['is_commit' => 1]);
			$tableCt = $this->XML2Arr($tableData['content']);
			# 写入统计数据
			// print_r($tableCt);die;
			foreach($tableCt['fundAppropriateData'] as $v){
				$statisticData = [
					'depart_id' => $tableCt['departId'],
					'depart_name' => $tableCt['departName'],
					'enter_name' => $tableCt['enterName'],
					'project_type' => $v['projectType'],
					'project_name' => $v['projectName'],
					'already' => $v['allocatedMoney'],
					'unalready' => $v['unAllocatedMoney'],
					'ratio' => $v['moneyRatio']
				];
				DB::name("statistics_capitalmgr")->insert($statisticData);
			}
			DB::commit();
			return ['code'=>1,'msg'=>'提交成功','data'=>''];
		}catch(\Exception $e){
			DB::rollback();
			return ['code'=>0,'msg'=>'提交失败','data'=>''];
		}
	}

	/**
	 * [固定资产表]
	 */
	# -< Asset >----------------------------------------------------------------
	public function Asset() {
		if($this->request->isPost()){
			$param = input("post.");
			$limit = $param['pageSize'];
            $offset = ($param['pageNumber'] - 1) * $limit;
            $where = [
				'depart_id' => $param['depart_id']
			];
			if($param['rpt_date']){
				$where['rpt_date'] = $param['rpt_date'];
			}
			if($param['link_man']){
				$where['link_man'] = ["like","%".$param['link_man']."%"];
			}
			if($param['link_type']){
				$where['link_type'] = ["like","%".$param['link_type']."%"];
			}
			$return['rows'] = DB::name("asset_rows")->where($where)
				->limit($offset,$limit)
				->order("id desc")
				->select();
			$return['total'] = DB::name("asset_rows")->where($where)->count();
			foreach($return['rows'] as &$v){
				if($v['rpt_date']){
					$v['rpt_date'] = date("Y年m月",$v['rpt_date']);
				}else{
					$v['rpt_date'] = "";
				}
				$v['price'] = sprintf("%01.2f", $v['price']);
			}
			return ['code'=>1,'msg'=>"加载成功","data"=>$return];
		}
		$depart = $this->getCurDepart();
		$this->assign([
			'depart' => $depart,
		]);
		return $this->fetch('write_asset');
	}
	/**
	 * [删除行]
	 * 1.表 asset_rows 更新 '删除备注' 和 '删除状态'
	 * 2.表 table_asset 根据row_ids找到对应的表格
	 * 3.操作对应的表格根据 row_ids 更新 content
	 */
	public function delAssetRow() {
		$param = input("post.");
		$param['del_remark'] = trim($param['del_remark']);
		if($param['del_remark'] == ''){
			return ['code'=>0,'msg'=>'删除备注不能为空'];
		}
		if(mb_strlen($param['del_remark']) > 32){
			return ['code'=>0,'msg'=>'删除备注字数超出，最大32个字符'];
		}
		DB::startTrans();
		try{
			# 1.表 asset_rows 更新 '删除备注' 和 '删除状态'
			DB::name('asset_rows')->where('id',$param['row_id'])->update([
				'is_del' => 1,'del_remark' => $param['del_remark']
			]);
			# 2.表 table_asset 根据row_ids找到对应的表格
			$tables = DB::name('table_asset')
				->where('row_ids','like',"%-".$param['row_id']."-%")->select();
			# 3.操作对应的表格根据 row_ids 更新 content
			foreach($tables as $table){
				$rowIdArr = array_merge(array_filter(explode("-",$table['row_ids'])));
				$this->editAsset($rowIdArr,$table['id']);
			}
			DB::commit();
			return ['code'=>1,'msg'=>'删除成功'];
		}catch(\Exception $e) {
			DB::rollback();
			return ['code'=>0,'msg'=>'删除失败:'.$e->getMessage()];
		}
	}

	public function editAsset($row_ids,$table_id) {
		$ct_arr = DB::name("asset_rows")->where('id','in',$row_ids)->select();
		$ct_xml = $this->Arr2XML($ct_arr);
		$res = DB::name('table_asset')->where('id',$table_id)->update([
			'content' => $ct_xml
		]);
		if($res !== false){
			return ['code'=>1,'msg'=>'success'];
		}else{
			return ['code'=>0,'msg'=>'error'];
		}
	}

	public function saveAssetRow() {
		$param = input('post.');
		$param['c_time'] = time();
		$depart = $this->getCurDepart();
		$param['depart_id'] = $depart['id'];
		$res = DB::name('asset_rows')->insert($param);
		if($res !== false){
			return ['code'=>1,'msg'=>'保存行成功'];
		}else{
			return ['code'=>0,'msg'=>'保存行失败'];
		}
	}

	public function saveAssetTable() {
		$param = input('post.');
		$param['rpt_date'] = $param['rpt_date']/1000;
		if($this->checkAsset($param['depart_id'],$param['rpt_date'])){
			return ['code'=>0,'msg'=>'保存表失败：该月份的报表已存在'];
		}
		$row_ids = $param['row_ids'];
		$param['row_ids'] = "-".implode("-",$row_ids)."-";
		$ct_arr = DB::name("asset_rows")->where([
			'depart_id' => $param['depart_id'],
			'id' => ['in',$row_ids]
		])->select();
		$param['content'] = $this->Arr2XML($ct_arr);
		$param['create_uid'] = session('id');
		$res = DB::name('table_asset')->insert($param);
		if($res !== false){
			return ['code'=>1,'msg'=>'保存表成功'];
		}else{
			return ['code'=>0,'msg'=>'保存表失败'];
		}
	}

	public function checkAsset($depart_id,$rpt_date) {
		$check = DB::name('table_asset')->where([
			'depart_id' => $depart_id,'rpt_date' => $rpt_date
		])->count();
		if($check != 0){
			return true;
		}else{
			return false;
		}
	}

	public function CommitAsset() {
		$table_id = input("post.table_id");
		$table = DB::name('table_asset')->where("id",$table_id)->find();
		if(empty($table)){
			return ['code'=>0,'msg'=>'参数传递错误'];
		}
		if($table['is_commit'] == 1){
			return ['code'=>0,'msg'=>'该表格已经提交，请勿重复提交'];
		}
		$row_ids = array_merge(array_filter(explode("-",$table['row_ids'])));
		DB::startTrans();
		try{
			DB::name('table_asset')->where("id",$table_id)->update([
			   'is_commit' => 1
		   	]);
			DB::name("asset_rows")->where("id",'in',$row_ids)->update([
				'rpt_date' => $table['rpt_date']
			]);
			DB::commit();
			return ['code'=>1,'msg'=>'提交成功'];
		}catch(\Exception $e){
			DB::rollback();
			return ['code'=>0,'msg'=>'提交失败,'.$e->getMessage()];
		}
	}

	public function delAsset() {
		$table_id = input("post.table_id");
		$res = DB::name('table_asset')->where("id",$table_id)->delete();
		if($res !== false){
			return ['code'=>1,'msg'=>'删除成功'];
		}else{
			return ['code'=>0,'msg'=>'删除失败'];
		}
	}

	/**
	 * [网店表]
	 */
	# -< Webshop >--------------------------------------------------------------
	public function webShop() {
		return $this->fetch();
	}

	public function webshopTable() {
		$company_id = input("get.company_id");
		$company = DB::name("users_company")->where("id",$company_id)->find();
		$this->assign([
			"Company" => $company
		]);
		return $this->fetch("write_webshoptable");
	}

	/**
	 * [获取网店报表]
	 */
	public function getWebshopForm() {
		$param = input("post.");
		$webshop = DB::name("webshop")->where("company_id",$param['company_id'])->select();
		$ct = [];
		foreach($webshop as $k => $v){
			$ct[$k] = [
				'webshop_name' => $v['name'],
				'webshop_url' => $v['url'],
				'webshop_remark' => $v['remark'],
				'pro_num' => '',
				'sales_amount' => '',
			];
		}
		if(empty($ct)){
			return ['code'=>0,'msg'=>'该企业还没有添加网店','data'=>''];
		}else{
			return ['code'=>1,'msg'=>'success','data'=>$ct];
		}
	}

	/**
	 * [保存网店报表]
	 */
	public function saveWebshopTable() {
		$param = input("post.");
		$param['rpt_date'] = $param['rpt_date'] / 1000;
		$param['content'] = $this->Arr2XML($param['content']);
		$is_save = $this->webshopTable_isSave($param);
		if($is_save){
			$is_commit = $this->webshopTable_isCommit($param);
			if($is_commit == 1){
				return ['code'=>0,'msg'=>'已提交的表格不能修改'];
			}
			$res = DB::name("table_webshop")->where([
				'company_id' => $param['company_id'],
				'depart_id' => $param['depart_id'],
				'rpt_date' => $param['rpt_date'],
				'create_uid' => $param['create_uid'],
			])->update($param);
		}else{
			$res = DB::name("table_webshop")->insert($param);
		}
		if($res !== false) {
			return ['code'=>1,'msg'=>'保存成功'];
		} else {
			return ['code'=>0,'msg'=>'保存失败'];
		}
	}

	/**
	 * [检查网店报表]
	 */
	public function webshopTable_isSave($param) {
		$count = DB::name("table_webshop")->where([
			'company_id' => $param['company_id'],
			'depart_id' => $param['depart_id'],
			'rpt_date' => $param['rpt_date'],
			'create_uid' => $param['create_uid'],
		])->count();
		if($count == 0){
			return false;
		}else{
			return true;
		}
	}
	public function webshopTable_isCommit($param) {
		return DB::name("table_webshop")->where([
			'company_id' => $param['company_id'],
			'depart_id' => $param['depart_id'],
			'rpt_date' => $param['rpt_date'],
			'create_uid' => $param['create_uid'],
		])->value('is_commit');
	}
}
